package cn.wonderland.community.controller;

import cn.wonderland.basic.util.BussinessException;
import cn.wonderland.community.domain.Owner;
import cn.wonderland.community.service.IHouseService;
import cn.wonderland.community.domain.House;
import cn.wonderland.community.query.HouseQuery;
import cn.wonderland.basic.util.AjaxResult;
import cn.wonderland.basic.util.PageList;
import cn.wonderland.community.service.IOwnerService;
import net.bytebuddy.implementation.bytecode.Throw;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/house")
public class HouseController {
    @Autowired
    public IHouseService houseService;
    @Autowired
    public IOwnerService ownerService;

    /**
     * 保存和修改公用的
     *
     * @param house 传递的实体
     * @return AjaxResult转换结果
     */
    @PutMapping
    public AjaxResult addOrUpdate(@RequestBody House house) {

        if (house.getId() != null) {
            houseService.update(house);
        } else {
            house.setCreateTime(new Date());
            houseService.add(house);
        }
        return AjaxResult.me().success();

    }

    /**
     * 删除对象信息
     *
     * @param id
     * @return
     */
    @DeleteMapping(value = "/{id}")
    public AjaxResult delete(@PathVariable("id") Long id) {
        Owner owner = ownerService.findByHouseId(id);
        if (owner != null) {
            throw new BussinessException("当前房屋已有业主，不能删除！");
        }
        houseService.delete(id);
        return AjaxResult.me().success();
    }

    //获取用户
    @GetMapping("/{id}")
    public House get(@PathVariable("id") Long id) {
        return houseService.findById(id);
    }


    /**
     * 查看所有的员工信息
     *
     * @return
     */
    @GetMapping()
    public List<House> list() {
        return houseService.findAll();
    }


    /**
     * 分页查询数据
     *
     * @param query 查询对象
     * @return PageList 分页对象
     */
    @PostMapping("/list")
    public PageList<House> json(@RequestBody HouseQuery query) {
        return houseService.queryByPage(query);
    }

    /**
     * 根据单元id查找房屋信息
     */
    @PostMapping("/findHouseByUnitId/{id}")
    public List<House> findHouseByUnitId(@PathVariable("id") Long id) {
        return houseService.findHouseByUnitId(id);
    }
}
